<template>
  <div>
    <div>
      <el-row>
        <el-col :span="12">
          <el-page-header @back="goBack" :content="productInfo.productName"></el-page-header>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button v-show="isUpdateProduct" icon="el-icon-close" class="ml-5" type="warning"
                     @click="canCelUpdateProduct">取消
          </el-button>
          <el-button v-show="isUpdateProduct" icon="el-icon-check" class="ml-5" type="success"
                     @click="successUpdateProduct">确认修改
          </el-button>
          <el-button v-show="!isUpdateProduct" icon="el-icon-delete" class="ml-5" type="danger" @click="deleteProduct">
            删除
          </el-button>
          <el-button v-show="!isUpdateProduct" icon="el-icon-edit" class="ml-5" type="primary"
                     @click="updateProduct(false)">
            编辑
          </el-button>
        </el-col>
      </el-row>
    </div>
    <div>
      <el-row :gutter="20">
        <el-col :span="10">
          <!--                    轮播图部分-->
          <div v-show="!isUpdateProduct">
            <el-carousel height="600px" :interval="5000" direction="vertical" :autoplay="true">
              <el-carousel-item v-for="item in productBanner" :key="item">
                <img :src="item" height="600px" alt="">
              </el-carousel-item>
            </el-carousel>
          </div>
          <!--                    修改封面和轮播图-->
          <div v-show="isUpdateProduct" style="height:600px">
            <el-row :gutter="20">
              <el-col :span="4">轮播图：</el-col>
              <el-col :span="16">
                <el-upload
                    class="avatar-uploader"
                    list-type="picture-card"
                    :action="`${$ysyApi}/api/UpLoadFile/`"
                    :headers="headers"
                    name="file"
                    :on-success="uploadProductBanner"
                    :on-remove="handleRemove"
                    :before-upload="beforeAvatarUpload">
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="4">封面图：</el-col>
              <el-col :span="16">
                <el-upload
                    class="avatar-uploader"
                    :action="`${$ysyApi}/api/UpLoadFile/`"
                    :headers="headers"
                    name="file"
                    :show-file-list="false"
                    :on-success="uploadProductCover"
                    :before-upload="beforeAvatarUpload">
                  <img v-if="ShowImageUrl" :src="ShowImageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="6">商品溯源信息：</el-col>
              <el-col :span="14">
                <el-button class="ml-5" type="primary" @click="fillProductTraceSource">重新获取商品溯源信息</el-button>
              </el-col>
            </el-row>
          </div>
        </el-col>
        <el-col :span="14" style="display: flex;flex-flow: column;justify-content: space-around;height: 600px">
          <!--                    商品条码-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">商品条码：</el-col>
              <el-col :span="16">
                <div v-show="!isUpdateProduct">{{ productInfo.productBar }}</div>
                <div v-show="isUpdateProduct">
                  <el-input
                      placeholder="请输入商品条码"
                      v-model="updateInfo.productBar"
                      clearable>
                  </el-input>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    商品名称-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">商品名称：</el-col>
              <el-col :span="16">
                <div v-show="!isUpdateProduct">{{ productInfo.productName }}</div>
                <div v-show="isUpdateProduct">
                  <el-input
                      placeholder="请输入商品名称"
                      v-model="updateInfo.productName"
                      clearable>
                  </el-input>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    商品类型-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">商品类型：</el-col>
              <el-col :span="16">
                <div v-show="!isUpdateProduct">{{ productInfo.productCategoryName }}</div>
                <div v-show="isUpdateProduct">
                  <el-select v-model="updateInfo.productType" placeholder="请选择您的商品类型">
                    <el-option v-for="item in productCategory" :key="item.productCategoryId"
                               :label="item.productCategoryName" :value="item.productCategoryId"></el-option>
                  </el-select>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    商品价格-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">商品价格：</el-col>
              <el-col :span="16">
                <div v-show="!isUpdateProduct">{{ productInfo.prodcutPrice }}</div>
                <div v-show="isUpdateProduct">
                  <el-input
                      placeholder="请输入商品价格"
                      v-model="updateInfo.prodcutPrice"
                      clearable>
                  </el-input>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    库存-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">商品库存：</el-col>
              <el-col :span="16">
                <div v-show="!isUpdateProduct">{{ productInfo.repertory }}</div>
                <div v-show="isUpdateProduct">
                  <el-input
                      type="number"
                      placeholder="请输入商品库存"
                      v-model="updateInfo.repertory"
                      clearable>
                  </el-input>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    商品位置-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">商品位置：</el-col>
              <el-col :span="16">
                <el-collapse accordion v-show="!isUpdateProduct">
                  <el-collapse-item>
                    <template slot="title">
                      {{ productInfo.sysConfigName }}
                    </template>
                    <div>经度：{{ productInfo.sysConfigContent.longitude }}</div>
                    <div>纬度：{{ productInfo.sysConfigContent.latitude }}</div>
                  </el-collapse-item>
                </el-collapse>
                <div v-show="isUpdateProduct">
                  <el-select v-model="updateInfo.sysConfigContent" placeholder="请选择您的商品状态">
                    <el-option v-for="item in productConfigAddress" :label="item.sysConfigName"
                               :value="item.sysConfigId"></el-option>
                  </el-select>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    商品层数-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">商品层数：</el-col>
              <el-col :span="16">
                <div v-show="!isUpdateProduct">{{ productInfo.productPlies }}</div>
                <div v-show="isUpdateProduct">
                  <el-input
                      type="number"
                      placeholder="请输入商品层数"
                      v-model="updateInfo.productPlies"
                      clearable>
                  </el-input>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    推荐指数-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">推荐指数：</el-col>
              <el-col :span="16">
                <div v-show="!isUpdateProduct">{{ productInfo.recommendationIndex }}</div>
                <div v-show="isUpdateProduct">
                  <el-input
                      type="number"
                      placeholder="请输入商品推荐指数"
                      v-model="updateInfo.recommendationIndex"
                      clearable>
                  </el-input>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    热门指数-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">热门指数：</el-col>
              <el-col :span="16">
                <div v-show="!isUpdateProduct">{{ productInfo.hotIndex }}</div>
                <div v-show="isUpdateProduct">
                  <el-input
                      type="number"
                      placeholder="请输入商品热门指数"
                      v-model="updateInfo.hotIndex"
                      clearable>
                  </el-input>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    销量-->
          <div v-show="!isUpdateProduct">
            <el-row :gutter="20">
              <el-col :span="4">销量：</el-col>
              <el-col :span="16">{{ productInfo.salesVolume }}</el-col>
            </el-row>
          </div>
          <!--                    浏览量-->
          <div v-show="!isUpdateProduct">
            <el-row :gutter="20">
              <el-col :span="4">浏览量：</el-col>
              <el-col :span="16">{{ productInfo.productCheckQuantity }}</el-col>
            </el-row>
          </div>
          <!--                    简介-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">商品简介：</el-col>
              <el-col :span="16">
                <div v-show="!isUpdateProduct">{{ productInfo.productIntro }}</div>
                <div v-show="isUpdateProduct">
                  <el-input
                      type="textarea"
                      maxlength="255"
                      :autosize="{ minRows: 6, maxRows: 6}"
                      placeholder="请输入商品简介"
                      show-word-limit
                      v-model="updateInfo.productIntro"
                      clearable>
                  </el-input>
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    创建时间-->
          <div v-show="!isUpdateProduct">
            <el-row :gutter="20">
              <el-col :span="4">
                <div class="">
                  创建时间：
                </div>
              </el-col>
              <el-col :span="16">
                <div class="">
                  {{ productInfo.createDatetime }}
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    修改时间-->
          <div v-show="!isUpdateProduct">
            <el-row :gutter="20">
              <el-col :span="4">
                <div class="">
                  修改时间：
                </div>
              </el-col>
              <el-col :span="16">
                <div class="">
                  {{ productInfo.updateDatetime }}
                </div>
              </el-col>
            </el-row>
          </div>
          <!--                    商品状态-->
          <div class="">
            <el-row :gutter="20">
              <el-col :span="4">
                <div class="">
                  商品状态：
                </div>
              </el-col>
              <el-col :span="16">
                <div class="" v-show="!isUpdateProduct">
                  <p v-if="productInfo.productStatus==0" style="color: #67C23A">在售</p>
                  <p v-if="productInfo.productStatus==1" style="color: #E6A23C">售罄</p>
                  <p v-if="productInfo.productStatus==2" style="color: #F56C6C">下架</p>
                </div>
                <div v-show="isUpdateProduct">
                  <el-select v-model="updateInfo.productStatus" placeholder="请选择您的商品状态">
                    <el-option label="在售" value="0"></el-option>
                    <el-option label="售罄" value="1"></el-option>
                    <el-option label="下架" value="2"></el-option>
                  </el-select>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-col>
      </el-row>
      <!--            商品溯源信息-->
      <el-row :gutter="20" style="margin: 20px 0px">
        <el-col :span="24">
          <div
              style="font-size: 18px;font-family: '微软雅黑';padding: 20px;background-color: #e9e9e9;border-radius: 15px;"
              v-html="productTraceSource"></div>
        </el-col>
      </el-row>
    </div>
    <!--        弹出警告框-->
    <el-dialog
        title="警告"
        :visible.sync="dangerDialogVisible"
        width="30%"
        :before-close="handleClose">
      <span>{{ dangerTitle }}</span>
      <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dangerDialogVisible = false">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ProductDetails",
  created() {
    this.productBar = this.$route.query.productBar
    this.getProductDetails()
    this.headers.Authorization = JSON.parse(localStorage.getItem('user')).token
  },
  data() {
    return {
      loginStatus: true,
      productBar: '',
      //上传封面进行展示
      ShowImageUrl: '',
      showBannerList: [],
      productCategory: [],
      dialogImageUrl: '',
      dialogVisible: false,
      dangerDialogVisible: false,
      disabled: false,
      dangerTitle: '',
      //图片上传请求头
      headers: {
        Authorization: ''
      },
      //是否位于修改
      isUpdateProduct: false,
      //获取到的商品信息
      productInfo: {
        productId: '', // 商品编号
        productBar: '', //商品条形码
        productType: '', //商品类型编号
        productCategoryName: '',//商品类型
        productPlaceAddress: '',//商品货架地址
        sysConfigContent: '',//商品货架位置
        productPlies: '',//商品货架层数
        recommendationIndex: '',//商品推荐指数
        hotIndex: '',//商品热门指数
        repertory: '',//商品库存数量
        salesVolume: '',//销量
        productCheckQuantity: '',//商品浏览量
        createDatetime: '', // 商品创建时间
        productStatus: '', //商品当前状态(0在售 1售罄 2下架)
        productIntro: '',//商品简介
        productCover: '', //商品封面
        productBanner: '', //商品轮播图
        productTraceSource: '', //商品溯源信息
        prodcutPrice: '', //商品价格
        productName: '', //商品名称
        updateDatetime: '', //修改时间
      },
      //展示所用溯源
      productTraceSource: '',
      //展示所用轮播图
      productBanner: [],
      //获取到的货架地址
      productConfigAddress: [],
      updateProductBanner: [],
      //用于修改商品信息
      updateInfo: {
        productId: '',
        productBar: '',
        productName: '',
        productType: '',
        productCategoryName: '',
        prodcutPrice: '',
        repertory: '',
        sysConfigName: '',
        sysConfigContent: '',
        recommendationIndex: '',
        hotIndex: '',
        productIntro: '',
        productStatus: '',
        productCover: '',//封面
        productBanner: "",//修改用的轮播图
      }
    }
  },
  methods: {
    //返回
    goBack() {
      this.$router.back()
    },
    //上传封面图片
    uploadProductCover(response, file, fileList) {
      this.ShowImageUrl = this.$ysyApi + response.message
      this.updateInfo.productCover = response.message
    },
    //修改banner图片
    uploadProductBanner(response, file, fileList) {
      this.updateProductBanner.push(response.message)
    },
    //删除banner图片
    handleRemove(file, fileList) {
      for (let i = 0; i < this.productBanner.length; i++) {
        if (this.showBannerList[i] == file.response.message) {
          this.showBannerList.splice(i, 1)
        }
      }
    },
    //判断上传文件是否为jpeg/png图片
    beforeAvatarUpload(file) {
      let isJPG = false;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        isJPG = true;
      }
      if (!isJPG) {
        this.$message.error('上传只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //获取解析商品信息
    getProductDetails(flag) {
      this.$axios({
        url: this.$api.FindProductDetails,
        method: 'get',
        params: {
          ProductBar: this.productBar
        }
      }).then(res => {
        if (res.code = 500 && res.msg == '您的登录过期') {
          if (this.loginStatus) {
            this.loginStatus = false
            this.$message.error('您的登录已经过期！请重新登录');
            localStorage.removeItem('user')
            this.$router.push({
              path: "/login"
            })
          }
          return
        } else if (res.code == 200 || res.code == false) {
          this.productInfo = res.data
          this.productBanner = []
          //解析轮播图
          let productBanner = JSON.parse(this.productInfo.productBanner)
          for (let i = 0; i < productBanner.length; i++) {
            this.productBanner.push(this.$ysyApi + productBanner[i])
          }
          //地址解析
          this.productInfo.sysConfigContent = JSON.parse(this.productInfo.sysConfigContent)
          if ((this.productInfo.productTraceSource === '' || this.productInfo.productTraceSource == null) && !flag) {
            this.fillProductTraceSource()
          } else {
            //解析溯源信息
            this.productInfo.productTraceSource = this.productInfo.productTraceSource.replace(/'/g, "\"").replace(/None/g, "\"\"").replace(/True/g, "\"True\"").replace(/False/g, "\"False\"")
            let productTraceSource = "<pre>" + JSON.stringify(JSON.parse(this.productInfo.productTraceSource)[0], null, 4) + "</pre>"
            this.productTraceSource = productTraceSource.replace(/\"\"/g, "暂无").replace(/\"/g, "")
          }
        }
      })
    },
    //删除商品
    deleteProduct() {
      this.$confirm('此操作将删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios({
          method: 'delete',
          url: this.$api.DeleteProduct,
          headers: {'content-type': 'multipart/form-data'},
          data: {
            'productId': this.productInfo.productId
          }
        }).then(res => {
          if (res.code === 200 || res.code == false) {
            this.$notify({
              title: '成功',
              message: '商品删除成功',
              type: 'success'
            });
            this.goBack()
          } else {
            this.$notify({
              title: '失败',
              message: res.msg,
              type: 'error'
            });
            this.load()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //获取所有货架位置
    findSysConfig() {
      this.$axios({
        url: this.$api.FindSysConfig,
        method: 'get',
        params: {
          sysConfigName: '商品货架位置'
        }
      }).then(res => {
        this.productConfigAddress = res.data
      })
    },
    //获取所有商品类型
    findProductCategory() {
      this.$axios({
        url: this.$api.FindProductCategory,
        method: 'get',
      }).then(res => {
        this.productCategory = res.data

      })
    },
    //重新获取溯源信息
    fillProductTraceSource() {
      this.$axios({
        url: this.$api.FillProductTraceSource,
        method: 'get',
        params: {
          SearchItem: this.productBar
        }
      }).then(res => {

        this.$notify({
          title: '成功',
          message: '溯源信息获取成功',
          type: 'success'
        });
        this.getProductDetails(true);
        this.updateProduct(true);

      })
    },
    //关闭警告提示框
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    },
    //点击编辑后，切换为input框
    updateProduct(flag) {
      //开始修改
      this.findSysConfig()
      this.findProductCategory()
      this.isUpdateProduct = !flag;
      this.updateInfo.productId = this.productInfo.productId
      this.updateInfo.productBar = this.productInfo.productBar
      this.updateInfo.productName = this.productInfo.productName
      this.updateInfo.productPlies = this.productInfo.productPlies
      this.updateInfo.productType = this.productInfo.productType
      this.updateInfo.prodcutPrice = this.productInfo.prodcutPrice
      this.updateInfo.repertory = this.productInfo.repertory
      this.updateInfo.sysConfigName = this.productInfo.sysConfigName
      this.updateInfo.sysConfigContent = ''
      this.updateInfo.recommendationIndex = this.productInfo.recommendationIndex
      this.updateInfo.hotIndex = this.productInfo.hotIndex
      this.updateInfo.productIntro = this.productInfo.productIntro
      this.updateInfo.productStatus = this.productInfo.productStatus
      this.updateInfo.productCover = this.productInfo.productCover
      this.updateInfo.productBanner = this.productInfo.productBanner
    },
    //点击取消后，切换为text
    canCelUpdateProduct() {
      //取消修改
      this.isUpdateProduct = false
    },
    //点击修改后，发送请求进行修改
    successUpdateProduct() {
      //开始修改操作
      if (this.updateInfo.sysConfigContent == '') {
        this.dangerTitle = '请选择该商品的位置'
        this.dangerDialogVisible = true
        return
      }
      for (let i = 0; i < this.updateProductBanner.length; i++) {
        if (i == 0) {
          this.updateInfo.productBanner = "["
        }
        this.updateInfo.productBanner += "\"" + this.updateProductBanner[i] + "\""
        if (i != this.updateProductBanner.length - 1) {
          this.updateInfo.productBanner += ","
        }
        if (i == this.updateProductBanner.length - 1) {
          this.updateInfo.productBanner += "]"
        }
      }
      this.$axios({
        url: this.$api.InsertProduct,
        method: 'post',
        headers: {
          'Authorization': JSON.parse(localStorage.getItem('user')).token,
          'content-type': 'multipart/form-data'
        },
        data: this.updateInfo
      }).then(res => {
        this.isUpdateProduct = false
        this.getProductDetails()
        this.$notify({
          title: '成功',
          message: '商品信息修改成功',
          type: 'success'
        });
        this.getProductDetails();
      })
    }
  }
}
</script>

<style>
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>